/* tslint:disable */
var createError = require("http-errors");
import express from "express";
import { Request, Response } from "express";
import { NextFunction } from "express-serve-static-core";
import compression from "compression"; // compresses requests
import bodyParser from "body-parser";
import dotenv from "dotenv";

// import flash from 'express-flash';
import path from "path";
import mongoose from "mongoose";

import passport from "passport";
import expressValidator from "express-validator";
import bluebird from "bluebird";

import { session, store } from "./session";

import auth from "./auth";

import firewall from "./firewall";

import * as config from "./config";

var cookieParser = require("cookie-parser");

var userRouter = require("./routes/user");
var configRouter = require("./routes/config");
var phoneCodeRouter = require("./routes/phoneCode");
var emailCodeRouter = require("./routes/emailCode");
var fileRouter = require("./routes/file");
var goodRouter = require("./routes/good");
import sliderCode from "./routes/sliderCode";
// Load environment variables from .env file, where API keys and passwords are configured
// dotenv.config({ path: ".env" });

const cors = require("cors");

// Create Express server
const app = express();

app.use(cookieParser());
app.use(compression());
// Express configuration
app.set("port", process.env.PORT || 3001);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(expressValidator());

// Connect to MongoDB
const mongoUrl = config.mongo.url;
(<any>mongoose).Promise = bluebird;
mongoose
  .connect(
    mongoUrl,
    { useMongoClient: true }
  )
  .then(() => {
    /** ready to use. The `mongoose.connect()` promise resolves to undefined. */
  })
  .catch(err => {
    console.log(
      "MongoDB connection error. Please make sure MongoDB is running. " + err
    );
    // process.exit();
  });

app.set("views", path.join(__dirname, "../views"));
app.set("view engine", "pug");

app.use(session);

app.use(async (req, res, next) => {
  //需要权限的接口
  const authLists: any[] = [];

  const needAuth = () => {
    let ret = false;
    authLists.forEach(d => {
      const url = new RegExp(d);
      if (url.test(req.originalUrl)) {
        ret = true;
      }
    });
    return ret;
  };

  if (!needAuth()) {
    next();
    return;
  }

  const hasSession = (userSession: any) => {
    return !!userSession;
  };

  const isLogin = (userSession: any) => {
    if (!hasSession(userSession)) {
      return false;
    }
    if (!userSession.isLogin) {
      return false;
    }
    return true;
  };

  const hasExpired = (userSession: any) => {
    const expired = new Date(userSession.cookie.expires).getTime();
    const now = new Date().getTime();
    if (now > expired) {
      return true;
    }
    return false;
  };

  const userSession = await store.get(req.session.id);

  if (isLogin(userSession)) {
    next();
    return;
  }

  res.json({
    code: 401,
    data: "get out of my system",
    msg: "fuck you hack"
  });
});

app.use(auth);

app.use("/user", userRouter);
app.use("/config", configRouter);

app.use("/phoneCode", phoneCodeRouter);
app.use("/emailCode", emailCodeRouter);
app.use("/file", fileRouter);
app.use("/good", goodRouter);
app.use("/sliderCode", sliderCode);

app.use("*", firewall);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err: any, req: Request, res: Response, next: NextFunction) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get("env") === "development" ? err : {};
  // render the error page
  res.status(err.status || 500);
  res.send(err.status);
});
export default app;
